import { http } from '@/utils/http'
import { SET_CHANNELS, SET_ARTICLE_LIST } from '@/store/actionTypes/article'

const setChannels = channels => {
  return {
    type: SET_CHANNELS,
    payload: channels
  }
}

const setArticleList = data => {
  return {
    type: SET_ARTICLE_LIST,
    payload: data
  }
}

// 获取频道列表
export const getChannels = () => {
  return async dispatch => {
    const { message, data } = await http.get('channels')

    if (message === 'OK') {
      dispatch(setChannels(data.channels))
    }
  }
}

// 获取文章列表
export const getArticleList = params => {
  return async dispatch => {
    const { message, data } = await http.get('mp/articles', {
      params
    })

    if (message === 'OK') {
      dispatch(
        setArticleList({ list: data.results, total_count: data.total_count })
      )
    }
  }
}

// 根据id，获取文章详情
export const getArticleInfo = async id => {
  const res = await http.get(`mp/articles/${id}`)

  return res.data
}

// 删除文章
export const delArticle = id => {
  return async () => {
    await http.delete(`mp/articles/${id}`)
  }
}

// 发布文章
export const publishArticle = data => {
  return async () => {
    await http.post('mp/articles', data)
  }
}

// 修改文章
export const editArticle = data => {
  return async () => {
    await http.put(`mp/articles/${data.id}`, data)
  }
}
